/*
 * Copyright 2008-2009 Daniel Cachapa <cachapa@gmail.com>
 * 
 * This program is distributed under the terms of the GNU General Public Licence Version 3
 * The licence can be read in its entirety in the LICENSE.txt file accompaning this source code,
 * or at: http://www.gnu.org/copyleft/gpl.html
 * 
 * This file is part of WeightWatch.
 *
 * WeightWatch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * WeightWatch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the WeightWatch source code. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package net.cachapa.weightwatch;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotOpenException;

public class Preferences {
	private static final String RS_NAME = "WeightWatchPrefs";
	private static final int HEIGHT_RECORD = 1;
	private static final int PLAN_RECORD = 2;
	private static final int LANG_RECORD = 3;
	private static final int METRIC_UNITS_RECORD = 4;
	private static final int ENERGY_UNIT_RECORD = 5;
	private static final int TOTAL_RECORDS = 5;
	
	private static final String DEFAULT_LANGUAGE = "en-uk";
	private static final String[] energyUnitLabels = {"kcal", "kj"};
	
	private RecordStore recordStore;
	// Preferences variables
	private double userHeight = 0;
	private String language = DEFAULT_LANGUAGE;
	private Plan plan;
	private boolean metricUnits = true;
	private int energyUnit = 0;
	
	public Preferences() {
		this.plan = new Plan();
		try {
			recordStore = RecordStore.openRecordStore(RS_NAME, true);
			int recordStoreSize = recordStore.getNumRecords();
			for (int i = recordStoreSize; i < TOTAL_RECORDS; i++) {	// We need to make sure that the records are created, so that we garantee that the indexes remain correct
				recordStore.addRecord(null, 0, 0);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		loadPreferences();
	}

	public void setUserHeight(double userHeight) {
		this.userHeight = userHeight;
		saveUserHeight();
	}

	public double getUserHeight() {
		return userHeight;
	}

	public void setLanguage(String language) {
		this.language = language;
		saveLanguage();
	}

	public String getLanguage() {
		if (language.equals("")) {
			return DEFAULT_LANGUAGE;
		}
		else {
			return language;
		}
	}
	
	public void setPlan(Plan plan) {
		this.plan = plan;
		savePlan();
	}

	public Plan getPlan() {
		return plan;
	}

	public void setMetricUnits(boolean metricUnits) {
		this.metricUnits = metricUnits;
		saveMetricUnits();
	}

	public boolean isMetricUnits() {
		return metricUnits;
	}
	
	public void setEnergyUnit(int value) {
		if (value < 0 || value > energyUnitLabels.length)
			return;
		this.energyUnit = value;
		saveEnergyUnit();
	}

	public String getEnergyUnit() {
		return energyUnitLabels[energyUnit];
	}
	
	private void saveUserHeight() {
		byte[] data = doubleToByteArray(userHeight);
		try {
			recordStore.setRecord(HEIGHT_RECORD, data, 0, data.length);
		} catch (InvalidRecordIDException ex) {
			try {
				recordStore.addRecord(data, 0, data.length);
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void savePlan() {
		byte[] data = plan.toByteArray();
		try {
			recordStore.setRecord(PLAN_RECORD, data, 0, data.length);
		} catch (RecordStoreNotOpenException ex) {
			ex.printStackTrace();
		} catch (InvalidRecordIDException ex) {
			try {
				recordStore.addRecord(data, 0, data.length);
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void saveLanguage() {
		byte[] data = language.getBytes();
		try {
			recordStore.setRecord(LANG_RECORD, data, 0, data.length);
		} catch (InvalidRecordIDException ex) {
			try {
				recordStore.addRecord(data, 0, data.length);
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void saveMetricUnits() {
		byte[] data = booleanToByteArray(metricUnits);
		try {
			recordStore.setRecord(METRIC_UNITS_RECORD, data, 0, data.length);
		} catch (InvalidRecordIDException ex) {
			try {
				recordStore.addRecord(data, 0, data.length);
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void saveEnergyUnit() {
		byte[] data = intToByteArray(energyUnit);
		try {
			recordStore.setRecord(ENERGY_UNIT_RECORD, data, 0, data.length);
		} catch (InvalidRecordIDException ex) {
			try {
				recordStore.addRecord(data, 0, data.length);
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void loadPreferences() {
		ByteArrayInputStream bin;
		DataInputStream din;
		try {
			byte[] heightData = recordStore.getRecord(HEIGHT_RECORD);
			bin = new ByteArrayInputStream(heightData);
			din = new DataInputStream(bin);
			userHeight = din.readDouble();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		try {
			byte[] planData = recordStore.getRecord(PLAN_RECORD);
			plan = new Plan();
			plan.fromByteArray(planData);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		try {
			byte[] langData = recordStore.getRecord(LANG_RECORD);
			language = new String(langData);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		try {
			byte[] metricUnitsData = recordStore.getRecord(METRIC_UNITS_RECORD);
			bin = new ByteArrayInputStream(metricUnitsData);
			din = new DataInputStream(bin);
			metricUnits = din.readBoolean();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void delete() {
		try {
			recordStore.closeRecordStore();
			RecordStore.deleteRecordStore(RS_NAME);
			recordStore = RecordStore.openRecordStore(RS_NAME, true);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public byte[] booleanToByteArray(boolean value) {
		try {
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			DataOutputStream dout = new DataOutputStream(bout);
			
			dout.writeBoolean(value);
			dout.flush();

			return bout.toByteArray();
		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	public byte[] intToByteArray(int value) {
		try {
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			DataOutputStream dout = new DataOutputStream(bout);
			
			dout.writeInt(value);
			dout.flush();

			return bout.toByteArray();
		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	public byte[] doubleToByteArray(double value) {
		try {
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			DataOutputStream dout = new DataOutputStream(bout);
			
			dout.writeDouble(value);
			dout.flush();

			return bout.toByteArray();
		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
	}
}
